﻿// requires a reference to System.Configuration, e.g. C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll
using System;
using System.Configuration;
using System.Xml;
//using System.Data.SqlClient;

//http://www.codeproject.com/Tips/280249/Programatically-update-connectionstring-using-Csha#alternative1
//Programatically update connectionstring using C#

namespace SaveConnectionStringDemo
{
	public class SaveConnectionString
	{
		/// <summary>
		/// Adds a connection string settings entry & saves it to the associated config file.
		///
		/// This may be app.config, or an auxiliary file that app.config points to or some
		/// other xml file.
		/// ConnectionStringSettings is the confusing type name of one entry including: 
		///			name + connection string + provider entry
		/// </summary>
		/// <param name="configuration">Pass in ConfigurationManager.OpenMachineConfiguration, 
		/// ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) etc. </param>
		/// <param name="connectionStringSettings">The entry to add</param>
		public static void AddAndSaveOneConnectionStringSettings(
			System.Configuration.Configuration configuration,
			System.Configuration.ConnectionStringSettings connectionStringSettings)
		{
			// You cannot add to ConfigurationManager.ConnectionStrings using
			// ConfigurationManager.ConnectionStrings.Add(connectionStringSettings) -- This fails.
			// But you can add to the configuration section and refresh the ConfigurationManager.

			// Get the connection strings section; Even if it is in another file.
			ConnectionStringsSection connectionStringsSection = configuration.ConnectionStrings;

			// Add the new element to the section.
			connectionStringsSection.ConnectionStrings.Add(connectionStringSettings);

			// Save the configuration file.
			configuration.Save(ConfigurationSaveMode.Minimal);

			// This is needed. Otherwise the updates do not show up in ConfigurationManager
			ConfigurationManager.RefreshSection("connectionStrings");
		}

        // Programatically update connectionstring using C#
        //B Birajdar
        //Programatically update connectionstring using C#
        //http://www.codeproject.com/Tips/280249/Programatically-update-connectionstring-using-Csha#alternative1

        public static void UpdateConnectionString(string ConfigPath)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(ConfigPath);
            XmlNode parentNode = xmlDocument.DocumentElement;
            if (parentNode.Name == "connectionStrings")
            {
                foreach (XmlNode childNode in parentNode.ChildNodes)
                {
                    if (childNode.Name == "add" && childNode.Attributes["name"].Value == "MySqlConnection")
                    {
                        string sqlConnectionString = childNode.Attributes["connectionString"].Value;

                        System.Data.SqlClient.SqlConnectionStringBuilder sqlBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder(sqlConnectionString);
                        sqlBuilder.InitialCatalog = "yourDatabaseName";
                        sqlBuilder.IntegratedSecurity = true;
                        sqlBuilder.Password = "";

                        //Change any other attributes using the sqlBuilder object
                        childNode.Attributes["connectionString"].Value = sqlBuilder.ConnectionString;
                    }
                }
            }
            xmlDocument.Save(ConfigPath);
        }
	}
}